package com.tanhua.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.commons.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter {
    @Value("${gateway.excludedUrls}")
    private String excludedUrls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();     //用户的请求路径
        List<String> excludedUrlsList = Arrays.asList(excludedUrls.split(","));
        if (excludedUrlsList.contains(path)) {
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("Authorization");
        if (!StringUtils.isEmpty(token)) {
            token = token.replaceAll("Bearer", "");
        }
        if (!JwtUtils.verifyToken(token)) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("errorCode", 401);
            resultMap.put("errMessage", "没有登录");

            try {
                response.getHeaders().set("content-type", "application/json;charset=utf-8");
                byte[] bytes = new ObjectMapper().writeValueAsBytes(resultMap);
                DataBuffer databuf = response.bufferFactory().wrap(bytes);
                return response.writeWith(Mono.just(databuf));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return chain.filter(exchange);
    }
}
